<template>
  <div class="app-container">
    <el-main id="main-content">
      <div class="content-wrapper">
        <!-- 搜索和操作区域 -->
        <div class="operation-area">
        <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
          <el-form-item>
            <el-input v-model="queryParams.keyword" placeholder="请输入地块ID或名称" clearable @keyup.enter="handleSearch">
              <template #append>
                <el-button :icon="Search" @click="handleSearch"></el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
            <el-button type="success" @click="handleAdd">添加秒杀活动</el-button>
          </el-form-item>
        </el-form>
        </div>

        <!-- 表格区域 -->
        <el-table 
          v-loading="loading" 
          :data="tableData" 
          border 
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="skid" label="秒杀ID" width="80" />
          <el-table-column prop="landid" label="地块ID" width="80" />
          <el-table-column prop="position" label="地块名称" min-width="120" />
          <el-table-column prop="skprice" label="秒杀价格" width="100">
            <template #default="scope">
              {{ scope.row.skprice }}元
            </template>
          </el-table-column>
          <el-table-column prop="sknum" label="秒杀数量" width="100" />
          <el-table-column prop="limitnum" label="限购数量" width="100" />
          <el-table-column prop="leasetime" label="租赁时间" width="120">
            <template #default="scope">
              {{ scope.row.leasetime }}天
            </template>
          </el-table-column>
          <el-table-column prop="sktime" label="秒杀时长" width="120">
            <template #default="scope">
              {{ scope.row.sktime }}小时
            </template>
          </el-table-column>
          <el-table-column prop="skstarttime" label="开始时间" min-width="180">
            <template #default="scope">
              {{ formatDate(scope.row.skstarttime) }}
            </template>
          </el-table-column>
          <el-table-column prop="state" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row)">
                {{ getStatusText(scope.row) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button type="primary" link @click="handleDetail(scope.row)">详情</el-button>
              <el-button type="success" link @click="handleEdit(scope.row)" v-if="!isActive(scope.row)">编辑</el-button>
              <el-button type="danger" link @click="handleLogicDelete(scope.row)" v-if="isActive(scope.row) && !isNotStarted(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>

        <!-- 秒杀活动表单对话框 -->
        <el-dialog
          :title="dialogTitle"
          v-model="dialogVisible"
          width="600px"
          @close="dialogClose"
        >
          <el-form
            ref="secondkillFormRef"
            :model="secondkillForm"
            :rules="formRules"
            label-width="100px"
          >
            <el-form-item label="地块" prop="landid">
              <el-select v-model="secondkillForm.landid" placeholder="请选择地块" filterable>
                <el-option 
                  v-for="item in landOptions" 
                  :key="item.landid" 
                  :label="`${item.position} (面积:${item.area}㎡)`" 
                  :value="item.landid" 
                />
              </el-select>
            </el-form-item>
            <el-form-item label="秒杀价格" prop="skprice">
              <el-input-number v-model="secondkillForm.skprice" :min="1" :precision="2" :step="0.01" controls-position="right" />
              <span class="unit">元</span>
            </el-form-item>
            <el-form-item label="秒杀数量" prop="sknum">
              <el-input-number v-model="secondkillForm.sknum" :min="1" :step="1" controls-position="right" />
              <span class="unit">个</span>
            </el-form-item>
            <el-form-item label="限购数量" prop="limitnum">
              <el-input-number v-model="secondkillForm.limitnum" :min="1" :step="1" controls-position="right" />
              <span class="unit">个/人</span>
            </el-form-item>
            <el-form-item label="租赁时间" prop="leasetime">
              <el-input-number v-model="secondkillForm.leasetime" :min="1" :step="1" controls-position="right" />
              <span class="unit">天</span>
            </el-form-item>
            <el-form-item label="秒杀时长" prop="sktime">
              <el-input-number v-model="secondkillForm.sktime" :min="1" :step="1" controls-position="right" />
              <span class="unit">小时</span>
            </el-form-item>
            <el-form-item label="开始时间" prop="skstarttime">
              <el-date-picker
                v-model="secondkillForm.skstarttime"
                type="datetime"
                placeholder="选择开始时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="submitForm">确 定</el-button>
            </div>
          </template>
        </el-dialog>

        <!-- 秒杀活动详情对话框 -->
        <el-dialog
          title="秒杀活动详情"
          v-model="detailVisible"
          width="700px"
        >
          <el-descriptions :column="2" border v-if="detailData.secondkill">
            <el-descriptions-item label="秒杀ID">{{ detailData.secondkill.skid }}</el-descriptions-item>
            <el-descriptions-item label="地块ID">{{ detailData.secondkill.landid }}</el-descriptions-item>
            <el-descriptions-item label="秒杀价格">{{ detailData.secondkill.skprice }}元</el-descriptions-item>
            <el-descriptions-item label="秒杀数量">{{ detailData.secondkill.sknum }}</el-descriptions-item>
            <el-descriptions-item label="限购数量">{{ detailData.secondkill.limitnum }}</el-descriptions-item>
            <el-descriptions-item label="租赁时间">{{ detailData.secondkill.leasetime }}天</el-descriptions-item>
            <el-descriptions-item label="秒杀时长">{{ detailData.secondkill.sktime }}小时</el-descriptions-item>
            <el-descriptions-item label="开始时间">{{ formatDate(detailData.secondkill.skstarttime) }}</el-descriptions-item>
            <el-descriptions-item label="结束时间">{{ formatDate(detailData.secondkill.skendtime) }}</el-descriptions-item>
            <el-descriptions-item label="状态" :span="2">
              <el-tag :type="getStatusType(detailData.secondkill)">
                {{ getStatusText(detailData.secondkill) }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>

          <el-divider content-position="center">地块信息</el-divider>
          
          <el-descriptions :column="2" border v-if="detailData.land">
            <el-descriptions-item label="地块名称">{{ detailData.land.position }}</el-descriptions-item>
            <el-descriptions-item label="地块面积">{{ detailData.land.area }}㎡</el-descriptions-item>
            <el-descriptions-item label="原价">{{ detailData.land.price }}元</el-descriptions-item>
            <el-descriptions-item label="库存">{{ detailData.land.stock }}</el-descriptions-item>
            <el-descriptions-item label="地址" :span="2">{{ detailData.land.address }}</el-descriptions-item>
            <el-descriptions-item label="描述" :span="2">{{ detailData.land.description }}</el-descriptions-item>
          </el-descriptions>

          <el-divider content-position="center">参与情况</el-divider>
          
          <el-table
            :data="detailData.orders || []"
            style="width: 100%"
            v-if="detailData.orders && detailData.orders.length > 0"
          >
            <el-table-column prop="orderid" label="订单ID" width="100" />
            <el-table-column prop="userid" label="用户ID" width="100" />
            <el-table-column prop="username" label="用户名称" min-width="120" />
            <el-table-column prop="num" label="数量" width="80" />
            <el-table-column prop="createtime" label="下单时间" min-width="180">
              <template #default="scope">
                {{ formatDate(scope.row.createtime) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="订单状态" width="100">
              <template #default="scope">
                <el-tag :type="getOrderStatusType(scope.row.status)">
                  {{ getOrderStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          <el-empty description="暂无订单数据" v-else></el-empty>
        </el-dialog>
      </div>
    </el-main>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import http from '@/utils/request'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const selectedRows = ref([])
const landOptions = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('') // 'add' 或 'edit'
const dialogTitle = ref('')
const secondkillFormRef = ref(null)
const secondkillForm = reactive({
  skid: undefined,
  landid: undefined,
  skprice: 0,
  sknum: 1,
  limitnum: 1,
  leasetime: 1,
  sktime: 5,
  skstarttime: '',
})

// 表单验证规则
const formRules = {
  landid: [
    { required: true, message: '请选择地块', trigger: 'change' }
  ],
  skprice: [
    { required: true, message: '请输入秒杀价格', trigger: 'blur' }
  ],
  sknum: [
    { required: true, message: '请输入秒杀数量', trigger: 'blur' }
  ],
  limitnum: [
    { required: true, message: '请输入限购数量', trigger: 'blur' }
  ],
  leasetime: [
    { required: true, message: '请输入租赁时间', trigger: 'blur' }
  ],
  sktime: [
    { required: true, message: '请输入秒杀时长', trigger: 'blur' }
  ],
  skstarttime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ]
}

// 详情对话框
const detailVisible = ref(false)
const detailData = reactive({
  secondkill: null,
  land: null,
  orders: []
})

// 日期格式化
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).replace(/\//g, '-');
}

// 判断秒杀活动状态
const isActive = (row) => {
  const now = new Date().getTime();
  const startTime = new Date(row.skstarttime).getTime();
  const endTime = row.skendtime ? new Date(row.skendtime).getTime() : 
                 (startTime + row.sktime * 60 * 1000);
  
  return now >= startTime && now <= endTime;
}

const getStatusType = (row) => {
  const now = new Date().getTime();
  const startTime = new Date(row.skstarttime).getTime();
  const endTime = row.skendtime ? new Date(row.skendtime).getTime() : 
                 (startTime + row.sktime * 60 * 1000);
  
  if (now < startTime) {
    return 'info';
  } else if (now >= startTime && now <= endTime) {
    return 'success';
  } else {
    return 'danger';
  }
}

const getStatusText = (row) => {
  const now = new Date().getTime();
  const startTime = new Date(row.skstarttime).getTime();
  const endTime = row.skendtime ? new Date(row.skendtime).getTime() : 
               (startTime + row.sktime * 60 * 60 * 1000);
  
  if (now < startTime) {
    return '未开始';
  } else if (now >= startTime && now <= endTime) {
    return '进行中';
  } else {
    return '已结束';
  }
}

const getOrderStatusType = (status) => {
  switch (status) {
    case 0: return 'info'; // 待支付
    case 1: return 'success'; // 已支付
    case 2: return 'danger'; // 已取消
    default: return 'info';
  }
}

const getOrderStatusText = (status) => {
  switch (status) {
    case 0: return '待支付';
    case 1: return '已支付';
    case 2: return '已取消';
    default: return '未知';
  }
}

// 获取表格数据
const getTableData = () => {
  loading.value = true
  http.get('/secondkill/list', { 
    params: {
      keyword: queryParams.keyword
    } 
  })
  .then(res => {
    console.log(res,'---------363');
    
    if (res.code === 200) {
      const secondkills = res.data.secondkills || []
      const landMap = res.data.landMap || {}
      
      const allData = secondkills.map(item => {
        const land = landMap[item.landid] || {}
        return {
          ...item,
          position: land.position || '未知地块'
        }
      })
      
      // 保存总数量
      total.value = allData.length
      
      // 前端分页处理
      const start = (queryParams.pageNum - 1) * queryParams.pageSize
      const end = start + queryParams.pageSize
      tableData.value = allData.slice(start, end)
    } else {
      ElMessage.error(res.message || '获取数据失败')
    }
  })
  .catch(error => {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败：' + error.message)
  })
  .finally(() => {
    loading.value = false
  })
}

// 获取可用地块列表
const getLandOptions = () => {
  http.get('/land/list')
    .then(res => {
      console.log(res,'---------399');
      
      if (res.code === 200) {
        landOptions.value = res.data || []
      } else {
        ElMessage.error(res.message || '获取地块列表失败')
      }
    })
    .catch(error => {
      console.error('获取地块列表失败:', error)
      ElMessage.error('获取地块列表失败：' + error.message)
    })
}

// 搜索方法
const handleSearch = () => {
  queryParams.pageNum = 1
  getTableData()
}

// 重置查询
const resetQuery = () => {
  queryParams.keyword = ''
  queryParams.pageNum = 1
  getTableData()
}

// 分页方法
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getTableData()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getTableData()
}

// 多选操作
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 添加秒杀活动
const handleAdd = () => {
  dialogType.value = 'add'
  dialogTitle.value = '添加秒杀活动'
  dialogVisible.value = true
  
  // 初始化表单
  secondkillForm.skid = undefined
  secondkillForm.landid = undefined
  secondkillForm.skprice = 0
  secondkillForm.sknum = 1
  secondkillForm.limitnum = 1
  secondkillForm.leasetime = 1
  secondkillForm.sktime = 5
  secondkillForm.skstarttime = ''
  
  // 获取地块列表
  getLandOptions()
}

// 编辑秒杀活动
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogTitle.value = '编辑秒杀活动'
  dialogVisible.value = true
  
  // 获取地块列表
  getLandOptions()
  
  // 填充表单数据
  Object.assign(secondkillForm, {
    skid: row.skid,
    landid: row.landid,
    skprice: row.skprice,
    sknum: row.sknum,
    limitnum: row.limitnum,
    leasetime: row.leasetime,
    sktime: row.sktime,
    skstarttime: row.skstarttime
  })
}

// 查看详情
const handleDetail = (row) => {
  detailVisible.value = true
  detailData.secondkill = null
  detailData.land = null
  detailData.orders = []
  
  // 获取秒杀活动详情
  http.get(`/secondkill/admin/detail/${row.skid}`)
    .then(res => {
      if (res.code === 200) {
        detailData.secondkill = res.data.secondkill || null
        detailData.land = res.data.land || null
        detailData.orders = res.data.orders || []
      } else {
        ElMessage.error(res.message || '获取详情失败')
      }
    })
    .catch(error => {
      console.error('获取详情失败:', error)
      ElMessage.error('获取详情失败：' + error.message)
    })
}

// 逻辑删除（修改状态）
const handleLogicDelete = (row) => {
  ElMessageBox.confirm('确认要删除该秒杀活动吗？删除后不可恢复', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 假设 status=3 表示已删除，具体值请根据后端定义调整
    http.put('/secondkill/admin/update', { skid: row.skid, state: 2 })
      .then(res => {
        if (res.code === 200) {
          ElMessage.success('删除成功')
          getTableData()
        } else {
          ElMessage.error(res.message || '删除失败')
        }
      })
      .catch(error => {
        console.error('删除失败:', error)
        ElMessage.error('删除失败：' + error.message)
      });
  }).catch(() => {
    ElMessage.info('已取消删除操作');
  });
}

// 提交表单
const submitForm = () => {
  if (!secondkillFormRef.value) return
  
  secondkillFormRef.value.validate((valid) => {
    if (valid) {
      if (dialogType.value === 'add') {
        // 发布秒杀活动
        http.post('/secondkill/publish', secondkillForm)
          .then(res => {
            if (res.code === 200) {
              ElMessage.success('添加成功')
              dialogVisible.value = false
              getTableData()
            } else {
              ElMessage.error(res.message || '添加失败')
            }
          })
          .catch(error => {
            console.error('添加失败:', error)
            ElMessage.error('添加失败：' + error.message)
          })
      } else {
        // 更新秒杀活动
        http.put('/secondkill/admin/update', {
          skid: secondkillForm.skid,
          state: 2
        })
          .then(res => {
            if (res.code === 200) {
              ElMessage.success('更新成功')
              dialogVisible.value = false
              getTableData()
            } else {
              ElMessage.error(res.message || '更新失败')
            }
          })
          .catch(error => {
            console.error('更新失败:', error)
            ElMessage.error('更新失败：' + error.message)
          })
      }
    }
  })
}

// 对话框关闭
const dialogClose = () => {
  secondkillFormRef.value?.resetFields()
}

// 页面加载时获取数据
onMounted(() => {
  getTableData()
})

// 判断秒杀活动是否未开始
const isNotStarted = (row) => {
  const now = new Date().getTime();
  const startTime = new Date(row.skstarttime).getTime();
  return now < startTime;
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.operation-area {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}

:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

.search-form :deep(.el-form-item) {
  margin-right: 10px;
}

.unit {
  margin-left: 8px;
  color: #666;
}
</style>